<template>

  <!-- 搜索词 -->
  <div v-loading="loading" :element-loading-text="loadingText">

    <div v-show="!checkedList.length" class="table-choose-box flex">
      <ul class="set flex">

        <li v-if="routeName==='seriesOverview'">
          <div>
            <el-select v-model="queryData.adgroupId" placeholder="请选择" size="small" @change="queryDataChange">
              <el-option label="全部广告组" value="" />
              <el-option v-for="(item,index) in allAdList" :key="item.adGroupId" :label="item.name" :value="item.adGroupId" />
            </el-select>
          </div>
        </li>
        <li>
          <span class="title">
            匹配来源
          </span>
          <div>
            <el-select v-model="queryData.matchType" placeholder="请选择" size="small" @change="queryDataChange">
              <el-option label="全部" value="" />
              <el-option label="关键词" value="BROAD" />
              <el-option label="搜索匹配" value="EXACT" />
            </el-select>
          </div>
        </li>

        <li>
          <powerSearch class="btn" :query-data="{...queryData.reportKeywordListCondition}" @click.native="highSearchShow=true"></powerSearch>
        </li>

      </ul>
      <div />

      <div class="handle flex">
        <div>
          <el-input v-model="queryData.name" size="small" placeholder="搜索搜索词" @keyup.enter.native="queryDataChange">
            <i slot="suffix" class="el-input__icon el-icon-search" @click="queryDataChange" />
          </el-input>
        </div>
        <em @click="thShowChange">设置显示字段</em>
        <em @click="dowLoadCsv">导出数据</em>
      </div>
    </div>

    <table-batch-handle v-show="checkedList.length" :num="checkedList.length" :del-show="false" :start-show="false"
      :pause-show="false">
      <em class="pointer" @click="setKeyWords('keyWords')">设置为关键词</em>
      <em class="pointer" @click="setKeyWords('negativeWords')">设置为屏蔽词</em>
    </table-batch-handle>

    <el-table :data="tableData" style="width: 100%;margin-top: 14px;" show-summary class="series-table" sortable="custom"
      :summary-method="returnTotal" @selection-change="tableCheckChange" @sort-change="tableSortChange">
      <el-table-column v-if="selectBtnShow&&caInfo.displayStatus !=='DELETED'&&adInfo.displaystatus !=='DELETED'" type="selection"
        width="45" :selectable="(row, index)=>{return row.searchTermText!=='(低展示词)'}" />

      <el-table-column label="搜索词" prop="searchTermText" width="220" fixed="left">
        <template slot-scope="scope">
          <div v-if="scope.row.searchTermText ==='(低展示词)'" class="">{{ scope.row.searchTermText }}</div>
          <div v-else class="pointer" @click="handleOneSearch(scope.row)">{{ scope.row.searchTermText }}</div>
        </template>
      </el-table-column>
      <el-table-column label="匹配来源" prop="searchTermText" width="100">
        <template slot-scope="scope">
          <div class="">{{ scope.row.searchTermSource==='TARGETED'?'关键词':'搜索匹配' }}</div>
        </template>
      </el-table-column>

      <el-table-column label="关键词" prop="keyword" align="center" width="220" />
      <el-table-column v-if="routeName==='seriesOverview'" label="广告组" width="200">
        <template slot-scope="scope">
          <div class="pointer overflow-ellipsis" @click="handlePush(scope.row.adGroupId)">{{ scope.row.adGroupId?scope.row.adGroupName:'-' }}</div>
        </template>
      </el-table-column>
      <template v-for="(item, index) in thListCopy">
        <el-table-column v-if="item.show" :key="index" :label="item.label" :prop="item.prop" :sortable="item.sort"
          :width="item.width||120" :align="item.align||'right'">
          <template slot-scope="scope">
            <div v-if="item.prop==='matchType'">
              <span class="keyWord_right">{{ scope.row.matchType==='EXACT'?'精确匹配':'模糊匹配' }}</span>
            </div>
            <div v-else>
              <span class="keyWord_right"  v-if="item.pre">{{ unitTxt }}</span>
              <span class="keyWord_right">{{ scope.row[item.prop] }}</span>
              <span class="keyWord_right" v-if="item.suf">{{ item.suf }}</span>
            </div>

          </template>
        </el-table-column>

      </template>
    </el-table>

    <div class="block" style="padding-top: 24px;display: flex;justify-content: flex-end;">
      <el-pagination :current-page="queryData.pageNum" :page-sizes="[10,20,30,40]" :page-size="10" layout="total, sizes, prev, pager, next, jumper"
        :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>

    <!-- 设置显示 -->
    <transfer-thead :default-th="thList" :th-list="thListCopy" :visible.sync="thVisible" @thListChange="handleSubThList" />

    <!-- 添加到关键词 -->
    <word-box ref="addWordBox" :max-num="caInfo.dailyBudgetAmount?caInfo.dailyBudgetAmount*1:caInfo.budgetAmount*1"
      :visible.sync="putShow" title="关键词" :fei-yong-show="true" :before-sub="handleClose" :appid="appid" :country-list="countryList"
      width="1200px" @handleSub="handleAddKeyWord">
      <div v-if="routeName==='seriesOverview'">
        <p style="width: 360px;display: flex; align-items: center;justify-content: space-between;">
          <span>添加至广告组</span>
          <em v-if="addAdList.length<allAdList.length" class="pointer" @click="handlePushAll">添加全部</em>
          <em v-else class="pointer" @click="addAdList=[]">移除全部</em>
        </p>
        <el-select v-model="addAdList" placeholder="请选择广告组" size="small" style="padding: 20px 0;width: 360px;" multiple>
          <el-option v-for="(item, index) in allAdList" :key="item.adGroupId" :label="item.name" :value="item.adGroupId" />
        </el-select>
      </div>
    </word-box>

    <!-- 添加否定关键词 手动-->
    <word-box ref="addNoWordBox" :visible.sync="putNoKeyShow" title="屏蔽词" :before-sub="handleBeforeUPWord" @handleSub="handleSubKey">
      <div style="overflow: hidden;">
        <div v-if="routeName==='seriesOverview'">
          <p>
            <span>添加至</span>
          </p>
          <div style="padding: 16px 0;display: flex; align-items: center; justify-content: space-between; width: 360px;">
            <div>
              <el-radio v-model="negateAddType" label="group">广告组</el-radio>
              <el-radio v-model="negateAddType" label="series">广告系列</el-radio>
            </div>
            <em v-if="negateAddGroupList.length<allAdList.length&&negateAddType=='group'" class="pointer" @click="handlePushAll">添加全部</em>
            <em v-if="negateAddGroupList.length>=allAdList.length&&negateAddType=='group'" class="pointer" @click="negateAddGroupList=[]">移除全部</em>
          </div>
        </div>

        <div v-if="routeName==='seriesOverview'&&negateAddType==='group'" style="padding-bottom: 20px;">
          <el-select v-model="negateAddGroupList" placeholder="请选择" size="small" multiple style="width: 360px;" @change="queryDataChange">
            <el-option v-for="(item,index) in allAdList" :key="item.adGroupId" :label="item.name" :value="item.adGroupId" />
          </el-select>
        </div>
      </div>

    </word-box>

    <!-- 显示搜索词详情 -->
    <searchWordDetails v-if="oneSearchShow" :show1.sync="oneSearchShow" :info="oneSearchInfo" :time-arr="timeArr" />

    <!-- 搜索词高级搜索 -->
    <el-dialog title="高级筛选" :visible.sync="highSearchShow" width="600px" class="bottom-dia" @open="handlerOpenHighSearch">
      <el-form :model="searchForm" :label-position="'top'" size="small">
        <el-row :gutter="80">
          <el-col :span="12">
            <el-form-item label="包含">
              <el-input v-model="searchForm.include" autocomplete="off" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="不包含">
              <el-input v-model="searchForm.denyWorder" autocomplete="off" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="花费">
              <intervalInput v-model="searchForm.localSpendAmount" suffix-show></intervalInput>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="展示">
              <intervalInput v-model="searchForm.impressions" :precision="0"></intervalInput>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="点击">
              <intervalInput v-model="searchForm.taps" :precision="0"></intervalInput>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="安装">
              <intervalInput v-model="searchForm.installs" :precision="0"></intervalInput>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="平均每次点击费用">
              <intervalInput v-model="searchForm.avgCptAmount" :suffix-show="true"></intervalInput>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="平均每次转化费用">
              <intervalInput v-model="searchForm.avgCpaAmount" :suffix-show="true"></intervalInput>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="点击率">
              <intervalInput v-model="searchForm.ttr" :suffix-show="true" suffix-txt="%"></intervalInput>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="转化率">
              <intervalInput v-model="searchForm.conversionRate" :suffix-show="true" suffix-txt="%"></intervalInput>
            </el-form-item>
          </el-col>

        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer flex">

		<em style="font-size: 14px;" @click="resetSearForm">重置</em>
        <div>
          <el-button class="cancel-btn" @click="highSearchShow=false">取 消</el-button>
          <el-button type="success" @click="handlerHighSearch">确 定</el-button>
        </div>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import tableBatchHandle from '../../components/table-batch-handle/index.vue'
  import transferThead from '../../components/transferThead.vue'
  import wordBox from '@/components/word-box.vue'
  import searchWordDetails from './searchWordDetails.vue'
  import {
    findReportSearchTermList, // 查询广告组下的搜索词表格
    findReportSearchTermListTotal, // 查询总计数据
    downloadSearchTermCsv, // 下载搜索词表格
    addKeyWords, // 添加关键词
    addNegativeKeyWords, // 添加屏蔽词
    addCampaignsNegativeKeyWords // 添加屏蔽词到广告系列

  } from '@/api/keyWord.js'

  export default {
    components: {
      tableBatchHandle,
      transferThead,
      wordBox,
      // upLoadWords,
      searchWordDetails
    },
    props: {
      timeArr: {
        type: Object,
        default: () => {
          return []
        }
      },
      maxNum: {
        type: Number || String,
        default: 12
      },
      adchannelType: {
        type: String,
        default: () => {
          return 'SEARCH'
        }
      }
    },
    data() {
      return {
        highSearchShow: false, // 高级筛选的弹框显示状态
        searchForm: {
          include: '', // 包含
          denyWorder: '', // 不包含
          localSpendAmount: { // 花费
            min: undefined,
            max: undefined
          },
          impressions: {
            min: undefined,
            max: undefined
          }, // 展示
          installs: {
            min: undefined,
            max: undefined
          }, // 安装||下载
          avgCptAmount: {
            min: undefined,
            max: undefined
          }, // cpt
          avgCpaAmount: {
            min: undefined,
            max: undefined
          }, // cpa
          ttr: {
            min: undefined,
            max: undefined
          }, // 点击率
          conversionRate: {
            min: undefined,
            max: undefined
          } // 转化率

        },
        oneSearchShow: false,
        oneSearchInfo: {},
        loading: true,
        loadingText: '数据加载中，请稍候',
        dialogVisible: false,
        csvUrl: '', // 模板下载路径
        /* 批量修改最高每次点击费用*/
        popoNunmber: undefined,
        popoShow: false,
        // 关键词添加
        putShow: false,
        addAdList: [], // 选中的广告组
        keywords: [],

        // 添加否定关键词
        putNoKeyShow: false,
        negateAddGroupList: [], // 选中的广告组
        negateAddType: 'group', // 选择添加屏蔽词到广告组还是广告系列

        // 关键词上传
        thVisible: false, // 设置字段的显示
        checkedList: [], // 选中的
        tableData: [],
        totalData: [],
        total: 0,
        queryData: {
          teamId: this.$store.state.team.teamId || '',
          currencyType: this.$route.query.currencyType || this.$store.state.user.unit,
          countrySX: this.$store.state.user.timeZone, // 时区
          timeZone: this.$store.getters.timeZoneTime, // 时区比UTC时间少几个小时
          adgroupId: this.$route.query.adgroupId || '',
          campaignId: '',
          endTime: this.$store.state.overview.timeObj.overViewTime.endTime,
          startTime: this.$store.state.overview.timeObj.overViewTime.startTime,
          name: '',
          order: 'descending',
          orgId: this.$route.query.orgId || '', // 如果是自助投放为空
          uuid: this.$route.query.uuid || '',
          aId: this.$route.query.aId || this.$route.query.aid || '',
          pageNum: 1,
          pageSize: 10,
          prop: 'status', // 选择项
          status: '',
          matchType: '',
          reportKeywordListCondition: {
            localSpendAmountMin: undefined,
            localSpendAmountMax: undefined,
            impressionsMin: undefined,
            impressionsMax: undefined,
            tapsMin: undefined,
            tapsMax: undefined,
            installsMin: undefined,
            installsMax: undefined,
            avgCptAmountMin: undefined,
            avgCptAmountMax: undefined,
            avgCpaAmountMin: undefined,
            avgCpaAmountMax: undefined,
            ttrMin: undefined,
            ttrMax: undefined,
            conversionRateMin: undefined,
            conversionRateMax: undefined,
            denyWorder: undefined
          }

        },
        /* 高级搜索表单*/
        searchForm: {
          include: '',
          denyWorder: '',
          localSpendAmount: {
            min: undefined,
            max: undefined
          },
          impressions: {
            min: undefined,
            max: undefined
          },
          taps: {
            min: undefined,
            max: undefined
          },
          installs: {
            min: undefined,
            max: undefined
          },
          avgCptAmount: {
            min: undefined,
            max: undefined
          },
          avgCpaAmount: {
            min: undefined,
            max: undefined
          },
          ttr: {
            min: undefined,
            max: undefined
          },
          conversionRate: {
            min: undefined,
            max: undefined
          }
        },
        thListCopy: [], // 表头
        thList: [{
            prop: 'matchType', // 属性
            label: '匹配类型', // 名称
            show: true, // 是否显示，
            sort: false, // 是否可以排序
            width: 240 // 宽度
          },
          {
            prop: 'localSpendAmount', // 属性
            label: '花费', // 名称
            show: true, // 是否显示，
            sort: true, // 是否可以排序
            pre: '$'
          },

          {
            prop: 'impressions', // 属性
            label: '展示', // 名称
            show: true, // 是否显示，
            sort: true // 是否可以排序
          },
          {
            prop: 'taps', // 属性
            label: '点击', // 名称
            show: true, // 是否显示，
            sort: true // 是否可以排序
          },
          {
            prop: 'installs', // 属性
            label: '安装', // 名称
            show: true, // 是否显示，
            sort: true // 是否可以排序
          },
          {
            prop: 'avgCpaAmount', // 属性
            label: '平均CPA', // 名称
            show: true, // 是否显示，
            sort: true, // 是否可以排序
            pre: '$'
          },
          {
            prop: 'avgCptAmount', // 属性
            label: '平均CPT', // 名称
            show: true, // 是否显示，
            sort: true, // 是否可以排序
            pre: '$'
          },

          {
            prop: 'ttr', // 属性
            label: '点击率', // 名称
            show: true, // 是否显示，
            sort: true, // 是否可以排序
            suf: '%'
          },
          {
            prop: 'conversionRate', // 属性
            label: '转化率', // 名称
            show: true, // 是否显示，
            sort: true, // 是否可以排序
            suf: '%'
          },
          {
            prop: 'newDownloads', // 属性
            label: '新增下载', // 名称
            show: false, // 是否显示，
            sort: true // 是否可以排序
          },
          {
            prop: 'redownloads', // 属性
            label: '重复下载', // 名称
            show: false, // 是否显示，
            sort: true // 是否可以排序
          },
          {
            prop: 'latOffinstalls', // 属性
            label: '开启LAT下载', // 名称
            show: false, // 是否显示，
            sort: true, // 是否可以排序
            width: 200 // 宽度
          },
          {
            prop: 'latOninstalls', // 属性
            label: '关闭LAT下载', // 名称
            show: false, // 是否显示，
            sort: true, // 是否可以排序
            width: 200 // 宽度
          }

        ]
      }
    },
    computed: {
      routeName() {
        return this.$route.name
      },
      // 选择的开始时间与结束时间
      timeObj() {
        return this.$store.state.overview.timeObj.overViewTime
      },
      appid() {
        const campaignId = this.$route.query.campaignId || this.$route.query.campaignid || ''
        const list = this.$store.state.overview.allCa
        const index = list.findIndex(item => {
          return campaignId * 1 === item.campaignId * 1
        })
        if (index !== -1) {
          return this.$store.state.overview.allCa[index].adamId
        } else {
          return ''
        }
      },

      countryList() {
        const campaignId = this.$route.query.campaignId || this.$route.query.campaignid || ''
        const list = this.$store.state.overview.allCa
        const index = list.findIndex(item => {
          return campaignId * 1 === item.campaignId * 1
        })
        const countrys = this.$store.state.overview.allCa[index].countriesOrRegions

        if (index !== -1) {
          if (countrys && countrys.length) {
            const str = countrys.substring(1, countrys.length - 1)

            return str.split(',')
          } else {
            return []
          }
        } else {
          return []
        }
      },
      // 广告组详情
      adInfo() {
        if (this.$route.name === 'seriesOverview') {
          return {
            displayStatus: this.caInfo.displayStatus
          }
        }
        const arr = this.$store.state.overview.allAd
        const index = arr.findIndex(item => {
          return item.adGroupId * 1 === this.$route.query.adGroupId * 1
        })
        return arr[index]
      },
      // 广告系列详情
      caInfo() {
        const arr = this.$store.state.overview.allCa
        const index = arr.findIndex(item => {
          return item.campaignId * 1 === this.$route.query.campaignId * 1
        })

        return arr[index]
      },
      allAdList() {
        return this.$store.state.overview.allAd
      },
      timeZone() {
        return this.$store.state.user.timeZone
      },
      unitTxt() {
        const unit = this.$store.state.user.unit
        this.$forceUpdate()
        return unit === 'RMB' ? '￥' : '$'
      },
      selectBtnShow() {
        if (this.$route.query.uuid && (this.$route.query.orgId || this.$route.query.orgid)) {
          const index = this.$store.state.overview.allAc.findIndex(item => {
            return item.uuid === this.$route.query.uuid
          })
          if (this.$store.state.overview.allAc[index].roleName === 'invalid_client') {
            return false
          }
          const i = this.$store.state.overview.allAc[index].org.findIndex(item => {
            return item.orgId === this.$route.query.orgId * 1 || item.orgId === this.$route.query.orgid * 1
          })
          const orgRole = this.$store.state.overview.allAc[index].org[i].roleName
          return orgRole !== 'API Read Only' && orgRole !== 'invalid_client' && !this.$isReadOnly(this.$store.state.user
            .userInfo.roleName)
        } else {
          return !this.$isReadOnly(this.$store.state.user.userInfo.roleName)
        }
      }
    },
    watch: {
      timeObj: {
        handler: function(newval, oldval) {
          this.queryData.pageNum = 1
          this.queryData.startTime = newval.startTime
          this.queryData.endTime = newval.endTime
          this.findReportSearchTermList()
          console.log(1)
          this.findReportSearchTermListTotal()
        },
        immediate: true,
        deep: true
      },

      timeZone: {
        deep: true,
        handler: function(newV, oldV) {
          this.queryData.pageNum = 1
          this.findReportSearchTermList()
           console.log(2)
          this.findReportSearchTermListTotal()
        }
      }

    },
    mounted() {
      // 表头
      if (localStorage.getItem('3yData_no_keyWords_Thlist')) {
        this.thListCopy = JSON.parse(localStorage.getItem('3yData_no_keyWords_Thlist'))
      } else {
        this.thListCopy = JSON.parse(JSON.stringify(this.thList))
      }
    },

    methods: {
      // 打开高级筛选显示框
      handlerOpenHighSearch() {
        const searchForm = this.searchForm
        for (const key in searchForm) {
          if (key === 'include') {
            this.searchForm.include = this.queryData.reportKeywordListCondition.include
          } else if (key === 'denyWorder') {
            this.searchForm.denyWorder = this.queryData.reportKeywordListCondition.denyWorder
          } else {
            this.searchForm[key].max = this.queryData.reportKeywordListCondition[key + 'Max'] ? this.queryData.reportKeywordListCondition[
              key + 'Max'] : undefined
            this.searchForm[key].min = this.queryData.reportKeywordListCondition[key + 'Min'] ? this.queryData.reportKeywordListCondition[
              key + 'Min'] : undefined
          }
        }
      },
      // 重置高级筛选
      resetSearForm() {
        this.searchForm = {
          include: '',
          denyWorder: '',
          localSpendAmount: {
            min: undefined,
            max: undefined
          },
          impressions: {
            min: undefined,
            max: undefined
          },
          taps: {
            min: undefined,
            max: undefined
          },
          installs: {
            min: undefined,
            max: undefined
          },
          avgCptAmount: {
            min: undefined,
            max: undefined
          },
          avgCpaAmount: {
            min: undefined,
            max: undefined
          },
          ttr: {
            min: undefined,
            max: undefined
          },
          conversionRate: {
            min: undefined,
            max: undefined
          }
        }
      },
      // 提交高级筛选
      handlerHighSearch() {
        const searchForm = this.searchForm
        for (const key in searchForm) {
          if (key === 'include') {
            this.queryData.reportKeywordListCondition.include = searchForm.include
          } else if (key === 'denyWorder') {
            this.queryData.reportKeywordListCondition.denyWorder = searchForm.denyWorder
          } else {
            this.queryData.reportKeywordListCondition[key + 'Max'] = this.searchForm[key].max ? this.searchForm[key].max :
              undefined
            this.queryData.reportKeywordListCondition[key + 'Min'] = this.searchForm[key].min ? this.searchForm[key].min :
              undefined
          }
        }
        this.highSearchShow = false
        this.queryData.pageNum = 1
        this.findReportSearchTermList()
        this.findReportSearchTermListTotal()
      },
      // 去广告组详情
      handlePush(id) {
        this.$router.push({
          name: 'groupOverview',
          query: {
            ...this.$route.query,
            adGroupId: id
          }
        })
      },
      handleOneSearch(data) {
        this.oneSearchInfo = JSON.parse(JSON.stringify(data))
        this.oneSearchShow = true
      },

      // 勾选数据
      tableCheckChange(data) {
        this.checkedList = JSON.parse(JSON.stringify(data))
      },

      /* 批量操作 */
      setKeyWords(type) {
        if (type === 'keyWords') {
          const arr = this.checkedList.map(item => {
            const obj = {
              text: item.searchTermText,
              matchType: 'BROAD',
              bidAmountNub: 0.01
            }
            return obj
          })
          if (this.$route.name === 'seriesOverview') {
            if (!this.allAdList.length) return this.$message.error('请先创建广告组')
            this.putShow = true
            this.addAdList = []
            this.$refs['addWordBox'].wordsData = arr
          } else {
            this.handleAddKeyWord(arr)
          }
        } else {
          const arr = this.checkedList.map(item => {
            const obj = {
              text: item.searchTermText,
              matchType: 'BROAD'
            }
            return obj
          })
          if (this.$route.name === 'seriesOverview') {
            this.putNoKeyShow = true
            this.negateAddGroupList = []
            this.$refs['addNoWordBox'].wordsData = arr
          } else {
            this.handleAddNoKey(arr)
          }
        }
      },
      // 添加全部广告组
      handlePushAll() {
        if (this.allAdList.length) {
          this.addAdList = this.allAdList.map(item => {
            return item.adGroupId
          })

          this.negateAddGroupList = this.allAdList.map(item => {
            return item.adGroupId
          })
        } else {
          return false
        }
      },

      // 添加||上传关键词之前所在的验证
      handleClose() {
        if (this.routeName === 'seriesOverview') {
          if (this.addAdList.length) return true
          this.$message.closeAll()
          this.$message.error('请选择广告组')
          return false
        }
        return true
      },

      // 添加||上传屏蔽词之前所在的验证
      handleBeforeUPWord() {
        if (this.negateAddType === 'group' && this.negateAddGroupList.length === 0 && this.routeName ===
          'seriesOverview') {
          this.$message.closeAll()
          this.$message.error('请先选择广告组')
          return false
        }
        return true
      },
      // 添加关键词
      async handleAddKeyWord(data) {
        const {
          adGroupId,
          campaignId
        } = this.$route.query
        const adArr = this.$route.name === 'seriesOverview' ? this.addAdList : [adGroupId]
        const requestArr = adArr.map(item => {
          const obj = {
            currencyType: this.$store.state.user.unit,
            campaignId,
            adGroupId: item,
            teamId: this.$store.state.team.teamId || '',
            orgId: this.$route.query.orgId || '', // 如果是自助投放为空
            uuid: this.$route.query.uuid || '',
            aId: this.$route.query.aId || this.$route.query.aid || '',
            userId: this.$store.state.user.userInfo.userId,
            keywords: JSON.parse(JSON.stringify(data))
          }
          return obj
        })
        const res = await addKeyWords(requestArr)
        if (res.data.code && res.data.code === 20000) {
          this.$message.closeAll()
          this.$message.success(res.data.message || '添加关键词成功')
        } else {
          this.$message.closeAll()
          this.$message.error(res.data.message || '服务器错误，请稍后重试')
        }
      },
      // 添加屏蔽词
      handleSubKey(data) {
        if (!data.length) return false
        if (this.negateAddType === 'group') {
          this.handleAddNoKey(data)
        } else {
          this.addNegativeKeyWordsToSeries(data)
        }
      },

      // 添加否定词到广告组
      async handleAddNoKey(data) {
        const {
          adGroupId,
          campaignId
        } = this.$route.query
        const adArr = this.$route.name === 'seriesOverview' ? this.negateAddGroupList : [adGroupId]
        const requestArr = adArr.map(item => {
          const obj = {
            teamId: this.$store.state.team.teamId || '',
            currencyType: this.$store.state.user.unit,
            campaignId,
            adGroupId: item,
            orgId: this.$route.query.orgId || '', // 如果是自助投放为空
            uuid: this.$route.query.uuid || '',
            aId: this.$route.query.aId || this.$route.query.aid || '',
            userId: this.$store.state.user.userInfo.userId,
            negativeKeyword: JSON.parse(JSON.stringify(data))
          }

          return obj
        })
        const res = await addNegativeKeyWords(requestArr)

        if (res.data.code && res.data.code === 20000) {
          this.$message.closeAll()
          this.$message.success(res.data.message || '添加否定关键词成功')
        } else {
          this.$message.closeAll()
          this.$message.error(res.data.message || '服务器错误，请稍后重试')
        }
      },

      // 添加屏蔽词到广告系列
      async addNegativeKeyWordsToSeries(data) {
        const {
          campaignId
        } = this.$route.query
        const obj = {
          teamId: this.$store.state.team.teamId || '',
          campaignId,
          orgId: this.$route.query.orgId || '', // 如果是自助投放为空
          uuid: this.$route.query.uuid || '',
          aId: this.$route.query.aId || this.$route.query.aid || '',
          userId: this.$store.state.user.userInfo.userId,
          campaignNegativeKeyword: JSON.parse(JSON.stringify(data)),
          currencyType: this.$route.query.currencyType || this.$store.state.user.unit
        }
        const res = await addCampaignsNegativeKeyWords(obj)
        this.$refs['addNoWordBox'].wordsData = []
        if (res.data.code && res.data.code === 20000) {
          this.$message.closeAll()
          this.$message.success(res.data.message || '添加屏蔽词成功')
        } else {
          this.$message.closeAll()
          this.$message.error(res.data.message || '服务器错误，请稍后重试')
        }
      },

      handleSizeChange(index) {
        this.queryData.pageSize = index
        this.queryData.pageNum = 1
        this.findReportSearchTermList()
        this.findReportSearchTermListTotal()
      },
      handleCurrentChange(index) {
        this.queryData.pageNum = index
        this.findReportSearchTermList()
        this.findReportSearchTermListTotal()
      },
      queryDataChange() {
        this.queryData.pageNum = 1
        this.findReportSearchTermList()
        this.findReportSearchTermListTotal()
      },

      // 排序变化
      tableSortChange(obj) {
        if (!obj.order) {
          this.queryData.prop = 'status'
          this.queryData.order = 'descending'
        } else {
          this.queryData.prop = obj.prop
          this.queryData.order = obj.order
        }
        this.queryData.pageNum = 1
        this.findReportSearchTermList()
        this.findReportSearchTermListTotal()
      },

      async findReportSearchTermList() {
        this.loading = true
        this.loadingText = '数据加载中，请稍候'
        this.queryData.adgroupId = this.$route.query.adGroupId || ''
        const res = await findReportSearchTermList({
          ...this.queryData,
          teamId: this.$store.state.team.teamId || '',
          campaignId: this.$route.query.campaignId || ''

        })
        if (res.data.code && res.data.code === 20000) {
          const {
            data
          } = res.data
          this.total = data.total
          const arr = JSON.parse(JSON.stringify(data.list))
          this.tableData = arr.map(item => {
            item.localSpendAmount = item.localSpendAmount * 1
            item.avgCpaAmount = item.avgCpaAmount * 1
            item.avgCptAmount = item.avgCptAmount * 1
            return item
          })
        } else {
          this.$message.closeAll()
          this.$message.error(res.data.message || '服务器错误，请稍后重试')
        }
        this.loading = false
      },

      // 对远程获取到的统计数据做出处理
      returnTotal(param) {
        const {
          columns
          // data
        } = param
        const sums = []
        columns.forEach((column, index) => {
          if (index === 2) {
            sums[index] = '总计'
            return
          } else {
            for (const key in this.totalData) {
              if (key === column.property) {
                switch (key) {
                  case 'localSpendAmount':
                    sums[index] = this.unitTxt + this.totalData[key]
                    break
                  case 'avgCpaAmount':
                    sums[index] = this.unitTxt + this.totalData[key]
                    break
                  case 'avgCptAmount':
                    sums[index] = this.unitTxt + this.totalData[key]
                    break
                  case 'ttr':
                    sums[index] = this.totalData[key] + '%'
                    break
                  case 'conversionRate':
                    sums[index] = this.totalData[key] + '%'
                    break

                  default:
                    sums[index] = this.totalData[key]
                    break
                }
              }
            }
          }
        })

        return sums
      },

      async findReportSearchTermListTotal() {
        this.loading = true
        this.loadingText = '数据加载中，请稍候'
        this.queryData.adgroupId = this.$route.query.adGroupId * 1 || ''
        this.queryData.campaignId = this.$route.query.campaignId * 1 || ''
        const res = await findReportSearchTermListTotal({
          ...this.queryData,
          teamId: this.$store.state.team.teamId || '',
          startTime: this.timeObj.startTime,
          endTime: this.timeObj.endTime,
          campaignId: this.$route.query.campaignId || '',
        })

        if (res.data.code && res.data.code === 20000) {
          const {
            data
          } = res.data
          this.totalData = JSON.parse(JSON.stringify(data[0]))
        } else {
          this.$message.closeAll()
          this.$message.error(res.data.message || '服务器错误，请稍后重试')
        }
        this.loading = false
      },

      // 设置显示字段
      thShowChange() {
        this.thVisible = true
      },

      handleSubThList(arr) {
        localStorage.setItem('3yData_no_keyWords_Thlist', JSON.stringify(arr))
        this.thListCopy = JSON.parse(JSON.stringify(arr))
      },
      // 导出数据
      async dowLoadCsv() {
        if (this.total < 1) {
          this.$message.closeAll()
          this.$message.error('暂无数据')
          return false
        }
        const obj = {
          ...this.queryData,
          pageNum: 1,
          pageSize: this.total,
          teamId: this.$store.state.team.teamId || '',
          orgId: this.$route.query.orgId || '', // 如果是自助投放为空
          uuid: this.$route.query.uuid || '',
          aId: this.$route.query.aId || this.$route.query.aid || '',
          startTime: this.timeArr[0],
          endTime: this.timeArr[1],
          adgroupId: this.$route.query.adGroupId,
          campaignId: this.$route.query.campaignId
        }

        const res = await downloadSearchTermCsv(obj)

        if (!res.data.message) {
          const blob = new Blob(['\ufeff' + res.data], {
            type: 'text/csv,charset=UTF-8'
          })
          const that = this
          const objectUrl = URL.createObjectURL(blob)
          const a = document.createElement('a')
          a.setAttribute('href', objectUrl)
          a.setAttribute('download', 'YYY_DATA_搜索词_' + that.queryData.startTime + '_' + this.queryData.endTime +
            '.csv')
          a.click()
        } else {
          this.$message.closeAll()
          this.$message.error(res.data.message || '导出数据失败，请稍后重试')
        }
      }

    }

  }
</script>

<style lang="scss" scoped>
  @import '../../components/handle.scss';
  .keyWord_right{
    position: relative;
    left:-12px;
  }
  // 设置表格总计样式
  div /deep/.el-table__footer-wrapper td.el-table__cell{
    position: relative !important;
    left: 2px !important;
  }
  .series-table {
    margin-top: 24px;

    /deep/ thead {
      th.el-table__cell.is-right>.cell {
        padding-left: 10px !important;
        padding-right: 24px;

        .caret-wrapper {
          position: absolute;
          top: 50%;
          right: 0;
          transform: translateY(-46%);
        }
      }
    }

    /deep/ .el-table__body {
      background: #FFFFFF;
	 /deep/  .el-table__cell.is-right>.cell{
	       padding-right: 24px;
	     }
    }
	/deep/ .el-table__footer-wrapper  .el-table__cell.is-right>.cell{
	     padding-right: 24px;
	   }

    /deep/ .del-row {
      background: rgba(57, 68, 78, 0.1);

      td,
      .cell {
        background: transparent !important;
      }
    }
  }
</style>
